package org.example.datastructure.ch2;

import java.util.LinkedList;

public class sLinkList<T> {
    public T val;
    public sLinkList<T> next;

    @Override
    public String toString() {
        return "sLinkList{" +
                "val=" + val +
                '}';
    }

    public sLinkList(T val) {
        this.val = val;
        this.next = null;
    }
    public sLinkList(T val, sLinkList<T> next) {
        this.val = val;
        this.next = next;
    }
    public sLinkList(){
        this.val = null;
        this.next = null;
    }
    public sLinkList move(int i){
        sLinkList head = this;
        while(i-->0){
            head = head.next;
        }
        return head;
    }
    public int getLength(){
        int length = 1;
        sLinkList head = this;
        while(head.next!= null){
            length++;
            head = head.next;
        }
        return length;
    }
    public void clear(){
        this.val = null;
        this.next = null;
    }
    public void insert(int i,sLinkList node){
        sLinkList head = this;
        while(i-->1){
            head = head.next;
        }
        node.next = head.next;
        head.next = node;
    }
    public void delete(int i){
        sLinkList head = this;
        while(i-->1){
            head = head.next;
        }
        head.next.clear();
        head.next = head.next.next;
    }
    public int search(T val){
        sLinkList head = this;
        int i = 0;
        while(head!=null && !head.val.equals(val)){
            head = head.next;
            i++;
        }
        if(head==null){
            return -1;
        }
        return i;
    }
    public T visit(int i){
        return (T) move(i).val;
    }
    public void traverse(){
        sLinkList head = this;
        while(head!=null){
            System.out.print(head.val+" ");

            head = head.next;
        }
        System.out.println();
    }

}



